package com.ft.controller;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ft.domain.Message;
import com.ft.domain.User;
import com.ft.domain.UserAddress;
import com.ft.service.IUserService;
import com.ft.utils.ArrayUtils;
import com.ft.utils.Code;
import com.ft.utils.Result;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author com/ft
 * @since 2022-08-24
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    IUserService userService;
    /**
     * 普通登录校验
     * @param user ：请求参数user对象
     * @param req http对象
     * @param
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest req){
        int a = userService.loginCheckUser(user.getName(),user.getPassword());
        if (a == 0) {
            return new Result(Code.POST_ERR,"手机号或密码不正确！");
        }else if (a == 1){
            User user1 = userService.selectUserByPhone(user.getName());
            req.getSession().setAttribute(String.valueOf(user1.getId()),user1.getId());
            return new Result(Code.POST_OK, user1,"登录成功");
        }else if (a == -2) {
            User user1 = userService.selectUserByID(user.getName());
            req.getSession().setAttribute(String.valueOf(user1.getId()),user1.getId());
            return new Result(Code.POST_OK, user1,"登录成功");
        }else {
            return new Result(Code.POST_ERR,"用户名或密码不正确！");
        }
    }

    /**
     * 短信登录服务
     * @return
     */
    @PostMapping("/{phone}/{code}")
    public Result loginsms(@PathVariable String phone,@PathVariable String code,HttpServletRequest req){
        int i = userService.PhoneLoginCheck(phone, code);
        if(i == 2){
            User user = userService.selectUserByPhone(phone);
            //登录后将用户id存入session
            req.getSession().setAttribute(String.valueOf(user.getId()),user.getId());
            return new Result(Code.POST_OK, user, "登录成功");
        }else if (i == 1) {
            return new Result(Code.POST_ERR,"验证码过期");
        }else if (i == 0) {
            return new Result(Code.POST_ERR,"验证码错误");
        }else{
            return new Result(Code.POST_ERR, "您首次登录创建用户失败，请重试或联系管理员");
        }
    }

    /**
     *发送手机验证码
     * @param phone 待发送验证码的手机号
     * @return
     */
    @GetMapping("/sendcode/{phone}")
    public Result check(@PathVariable String phone){
        int i = userService.sendMessage(phone);
        if(i == 2){
            return new Result(Code.GET_OK, "验证码发送成功");
        }else if(i == 1){
            return new Result(Code.GET_ERR,"请等待1分钟后重试！");
        }else if (i == 3){
            return new Result(Code.GET_ERR, "一小时只能发送5次验证码！");
        }else if (i == 4) {
            return new Result(Code.GET_ERR, "一天只能发送10次验证码！");
        }else {
            return new Result(Code.GET_ERR, "验证码发送失败！");
        }
    }


    /**
     * 注册接口
     * @param user 传入的用户信息
     * @param req 请求对象
     * @return 返回对应的是否注册成功的信息
     */
    @PostMapping()
    public Result addUser(@RequestBody User user,HttpServletRequest req){
        int b = userService.addUser(user);
        System.out.println(b);
        if (b == 0) {
            return new Result(Code.POST_OK, "注册成功！");
        }else if (b == 1){
            return new Result(Code.POST_ERR, "注册失败！");
        }else {
            return new Result(Code.POST_ERR, "用户名以存在！");
        }
    }

    /**
     *查询所有state状态不为2的用户，为2是逻辑删除
     * @return 返回没有删除的所用用户
     */
    @GetMapping("")
    public Result selectAll(){
        List<User> users = userService.selectAll();
        return new Result(Code.GET_OK,users,"查询全部信息成功");
    }

    /**
     * 删除用户，做逻辑删除，设置用户state为2
     * @param id 要删除的id
     * @return 返回删除结果
     */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable int id){
        int i = userService.deleteUser(id);
        if(i == 1){
            return new Result(Code.DELETE_OK, "删除成功");
        }else {
            return new Result(Code.DELETE_ERR, "删除失败！");
        }
    }

    /**
     * 修改用户信息
     * @param user 修改的用户信息
     * @return 返回修改的结果
     */
    @PutMapping("")
    public Result updateUser(@RequestBody User user) {
        int i = userService.updateUser(user);
        if (i == 1) {
            return new Result(Code.PUT_OK, "修改成功");
        }else {
            return new Result(Code.PUT_ERR, "修改失败");
        }
    }

    /**
     * 根据传入的页码查询页面的数据
     * @param page 要查询的第几页的页码
     * @return 返回查询的List结果集
     */
    @GetMapping("/{page}")
    public List<User> selectDataByPage(@PathVariable int page) {
        List<User> users = userService.selectDataByPage(page);
        return users;
    }

    /**
     * 查询已经逻辑删除的用户
     * @return 返回查询的list集合
     */
    @GetMapping("/state")
    public Result selectByUserState(){
        List<User> users = userService.selectByState();
        System.out.println(users);
        return new Result(Code.GET_OK, users,"查询成功");
    }

    /**
     * 获取用户好友列表信息
     * @return 好友列表集合
     */
    @GetMapping("/getuserlist/{userid}")
    public Result getUserList(@PathVariable String userid){
        List<User> userList = userService.getUserList(userid);
        if(userList.size() > 0){
            return new Result(Code.GET_OK, userList, "获取好友信息成功");
        }else if(userList.size() == 0) {
            return new Result(Code.GET_OK, userList,"获取好友信息成功，用户好友列表为空");
        }else {
            return new Result(Code.GET_ERR, userList,"获取好友信息失败");
        }
    }

    /**
     * 根据传入的地址增加用户地址信息
     * @param ud 用户对象信息
     * @return
     */
    @PostMapping("/address")
    public Result addUserAddress(@RequestBody String ud) throws Exception {
        UserAddress s1 = JSON.parseObject(ud, UserAddress.class);
        int i = userService.addUserAddress(s1,s1.getId());
        if(i == 0){
            return new Result(Code.POST_ERR,"增加地址失败!");
        }else if(i == 1) {
            List<UserAddress> list = userService.selectAddress(s1.getId());
            return new Result(Code.POST_OK,list, "增加地址成功!");
        }else {
            return new Result(Code.POST_ERR,"您只能拥有3个地址！");
        }
    }

    /**
     * 查询用户地址信息
     * @param id 用户id
     * @return 返回地址集合
     * @throws JsonProcessingException
     */
    @GetMapping("/address/{id}")
    public Result selectAddress(@PathVariable int id) throws JsonProcessingException {
        List<UserAddress> list = userService.selectAddress(id);
        if(list.size() == 0 || list.size() == 1 & (list.get(0).getAddress()).equals("")) {
            return new Result(Code.GET_ERR,"用户地址信息为空！");
        }else{
            return new Result(Code.GET_OK,list, "获取用户地址成功！");
        }
    }

    /**
     *
     * @param id 删除地址的用户id
     * @param index 删除的地址下标
     * @return 成功获取失败
     */
    @DeleteMapping("/address/{id}/{index}")
    public Result deleteUserAddress(@PathVariable int id, @PathVariable int index){
        int i = userService.deleteUserAddress(id, index);
        if(i == 0){
            return new Result(Code.DELETE_ERR,"删除地址失败!");
        }else{
            return new Result(Code.DELETE_OK,"删除用户地址成功!");
        }
    }
    @PutMapping("/address/{id}")
    public Result updateAddress( @PathVariable int id,@RequestBody String ud) throws Exception {
        ArrayList<UserAddress> s1 = ArrayUtils.atoString(ud);
        int i = userService.updateUserAddress(id,s1);
        if(i == 0){
            return new Result(Code.PUT_ERR,"修改地址失败");
        }else {
            return new Result(Code.PUT_OK,"修改用户地址成功");
        }
    }
    @GetMapping("/usersex/{id}")
    public Result getUserSex(int id){
        int userSex = userService.getUserSex (id);
        return new Result(Code.GET_OK,userSex,"获取成功");
    }
    /**
     *发送重置密码验证码
     * @param phone 待发送验证码的手机号
     * @return
     */
    @GetMapping("/resetcode/{phone}")
    public Result resetPhoneCode(@PathVariable String phone){
        int i = userService.wjmmSendMessage(phone);
        if(i == 2){
            return new Result(Code.GET_OK, "验证码发送成功");
        }else if(i == 1){
            return new Result(Code.GET_ERR,"请等待1分钟后重试！");
        }else if (i == 3){
            return new Result(Code.GET_ERR, "一天最多重置3次密码");
        }else {
            return new Result(Code.GET_ERR, "验证码发送失败！");
        }
    }
    @PutMapping("/resetpossword/{phone}/{code}/{password}")
    public Result resetPossword(@PathVariable String phone,@PathVariable String code, @PathVariable String password){
        int i = userService.resetPassword(phone, code, password);
        if(i == 1){
            return new Result(Code.PUT_OK, "修改密码成功");
        }else {
            return new Result(Code.PUT_ERR, "修改密码失败");
        }
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/userinfo/{id}")
    public Result getUserInfoById(@PathVariable int id){
        User user = userService.selectUserInfoById(id);
        if(user == null){
            return new Result(Code.GET_ERR,"用户不存在！");
        }else {
            return new Result(Code.GET_OK,user,"获取成功");
        }
    }

    /**
     * 获取用户离线消息
     * @return
     */
    @GetMapping("/userOffline/{userid}")
    public Result getOfflineUsermessage(@PathVariable int userid){
        List<Message> offlineUsermessage = userService.getOfflineUsermessage(userid);
        return new Result(Code.GET_OK,offlineUsermessage,"获取成功");
    }

    /**
     * 添加用户离线信息
     * @param message
     * @return
     */
    @PostMapping("/adduseroffline")
    public Result addOfflineUsermessage(@RequestBody Message message) throws IllegalAccessException{
        int i = userService.addOfflineUsermessage(message);
        if(i == 1){
            return new Result(Code.POST_OK, "添加成功");
        }else {
            return new Result(Code.POST_ERR, "添加失败");
        }
    }

    /**
     * 删除用户离线信息
     * @param userid
     * @return
     */
    @DeleteMapping("/deleteuseroffline/{userid}")
    public Result deleteOfflineUsermessage(@PathVariable int userid){
        int i = userService.deleteOfflineUsermessage(userid);
        if(i == 1){
            return new Result(Code.DELETE_OK, "删除成功");
        }else {
            return new Result(Code.DELETE_ERR, "删除失败");
        }
    }

    @PutMapping("/adduserfriend/{userid}/{touserid}")
    public Result addUseridToUserList(@PathVariable String userid, @PathVariable int touserid){
        int i = userService.addUserFrientList(userid,touserid);
        if(i == 1){
            return new Result(Code.PUT_OK,"添加成功");
        }else{
            return new Result(Code.PUT_ERR,"添加失败");
        }
    }
    @PutMapping("/updateuserinfo")
    public Result updateUserInfo(@RequestBody User user){
        int i = userService.updateUserInfo(user);
        if(i == 1){
            return new Result(Code.PUT_OK,"更新信息成功");
        }
        return new Result(Code.PUT_ERR,"更新信息失败");
    }

    @GetMapping("/money/{userid}")
    public Result getUserMeney(@PathVariable int userid){
        double userMeney = userService.getUserMeney(userid);
        return new Result(Code.GET_OK,""+userMeney,"获取成功");
    }
}

